<template>
  <div>
    <el-card class="box-1">
      <div slot="header"><span>{{ title }}</span></div>
      <el-form ref="form" :model="form" :rules="formRules" label-width="160px">
        <el-form-item label="客户昵称" prop="name">
          <div v-if="isDetails">{{ form.name }}</div>
          <el-input v-else v-model="form.name" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <div v-if="isDetails">{{ form.realname }}</div>
          <el-input v-else v-model="form.realname" />
        </el-form-item>
        <el-form-item label="协助者">
          <div v-if="isDetails">{{ form.follow_list }}</div>
        </el-form-item>
        <el-form-item label="公司">
          <div v-if="isDetails">{{ form.company }}</div>
          <div v-if="!isDetails">
            <el-input v-for="(companyItem, companyIndex) in form.company" v-model="form['company'][companyIndex]" :key="companyIndex" placeholder="请输入公司名称">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('company', companyItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('company')">新增公司名</el-button>
          </div>
        </el-form-item>
        <el-form-item label="职位">
          <div v-if="isDetails">{{ form.position }}</div>
          <el-input v-else v-model="form.position" />
        </el-form-item>
        <el-form-item label="客户手机" prop="mobile">
          <div v-if="isDetails">{{ form.mobile }}</div>
          <el-input v-else v-model="form.mobile" placeholder="请输入主要手机号码"/>
        </el-form-item>
        <el-form-item label="其他手机">
          <div v-if="isDetails">{{ form.spare_mobile }}</div>
          <div v-if="!isDetails">
            <el-input v-for="(mobileItem, mobileIndex) in form.spare_mobile" v-model="form['spare_mobile'][mobileIndex]" :key="mobileIndex" placeholder="请输入其他联系手机号码">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('spare_mobile', mobileItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('spare_mobile')">新增手机号</el-button>
          </div>
        </el-form-item>
        <el-form-item label="座机">
          <div v-if="isDetails">{{ form.telephone }}</div>
          <div v-if="!isDetails">
            <el-input v-for="(telephoneItem, telephoneIndex) in form.telephone" v-model="form['telephone'][telephoneIndex]" :key="telephoneIndex" placeholder="请输入座机">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('telephone', telephoneItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('telephone')">新增座机</el-button>
          </div>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <div v-if="isDetails">{{ form.type===0?'个人':'企业' }}</div>
          <el-select v-else v-model="form.type" placeholder="请选择类型">
            <el-option :value="0" label="个人" />
            <el-option :value="1" label="企业" />
          </el-select>
        </el-form-item>
        <el-form-item label="腾讯云ID">
          <div v-if="isDetails">{{ form.qq }}</div>
          <div v-if="!isDetails">
            <el-input v-for="(qqItem, qqIndex) in form.qq" v-model="form['qq'][qqIndex]" :key="qqIndex" placeholder="请输入腾讯云ID">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('qq', qqItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('qq')">新增腾讯云ID</el-button>
          </div>
        </el-form-item>
        <el-form-item label="微信">
          <div v-if="isDetails">{{ form.wechat }}</div>
          <div v-if="!isDetails">
            <el-input v-for="(wechatItem, wechatIndex) in form.wechat" v-model="form['wechat'][wechatIndex]" :key="wechatIndex" placeholder="请输入微信号">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('wechat', wechatItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('wechat')">新增微信</el-button>
          </div>
        </el-form-item>
        <el-form-item label="QQ">
          <div v-if="isDetails">{{ form.tencent_id }}</div>
          <div v-if="!isDetails">
            <el-input v-for="(tencentIdItem, tencentIdIndex) in form.tencent_id" v-model="form['tencent_id'][tencentIdIndex]" :key="tencentIdIndex" placeholder="请输入QQ">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('tencent_id', tencentIdItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('tencent_id')">新增QQ号</el-button>
          </div>
        </el-form-item>
        <el-form-item label="邮箱">
          <div v-if="isDetails">{{ form.email }}</div>
          <div v-if="!isDetails">
            <el-input v-for="(emailItem, emailIndex) in form.email" v-model="form['email'][emailIndex]" :key="emailIndex" placeholder="请输入邮箱">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('email', emailItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('email')">新增邮箱</el-button>
          </div>
        </el-form-item>
        <el-form-item label="客户来源" prop="source">
          <div v-if="isDetails">{{ form.source }}</div>
          <el-select v-else v-model="form.source" filterable placeholder="请选择客户来源">
            <el-option v-for="item in sourceList" :key="item.id" :label="item.source_name" :value="item.source_name" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!id" label="沟通记录">
          <el-input v-model="form['one_log']" type="textarea" rows="4"/>
        </el-form-item>
        <el-form-item label="备注">
          <div v-if="isDetails"><pre class="pre">{{ form.remarks }}</pre></div>
          <el-input v-else v-model="form.remarks" type="textarea" rows="4"/>
        </el-form-item>
        <div style="text-align:center">
          <el-button v-if="isDetails" type="primary" @click="toModify">编辑</el-button>
          <el-button v-else :loading="submitDisabled" :disabled="submitDisabled" type="primary" @click="submitForm('form')">确定</el-button>
          <el-button type="primary" @click="cancel">取消</el-button>
        </div>
      </el-form>
      <h5 class="margin-top-20">● 修改历史</h5>
      <el-collapse v-model="activeNames">
        <el-collapse-item v-for="(item, index) in updateLog" :key="index" :title="item.created_at + '（ 修改人：' + item.u_name + ' ）'" :name="index">
          <el-card>
            <el-form label-width="160px">
              <el-form-item label="客户昵称">{{ item['c_info'].name }}</el-form-item>
              <el-form-item label="真实姓名">{{ item['c_info'].realname }}</el-form-item>
              <el-form-item label="协助者">{{ item['c_info'].follow_list }}</el-form-item>
              <el-form-item label="公司">{{ item['c_info'].company }}</el-form-item>
              <el-form-item label="职位">{{ item['c_info'].position }}</el-form-item>
              <el-form-item label="客户手机">{{ item['c_info'].mobile }}</el-form-item>
              <el-form-item label="类型">{{ item['c_info'].type===0?'个人':'企业' }}</el-form-item>
              <el-form-item label="腾讯云ID">{{ item['c_info'].qq }}</el-form-item>
              <el-form-item label="微信">{{ item['c_info'].wechat }}</el-form-item>
              <el-form-item label="邮箱">{{ item['c_info'].email }}</el-form-item>
              <el-form-item label="客户来源">{{ item['c_info'].source }}</el-form-item>
              <el-form-item label="备注">{{ item['c_info'].remarks }}</el-form-item>
            </el-form>
          </el-card>
        </el-collapse-item>
      </el-collapse>
    </el-card>
  </div>
</template>

<script>
import { validatNonSpecialCharactersNonPureNumber, validatNonSpecialCharacters } from '@/utils/validate'
export default {
  data() {
    return {
      title: '',
      isDetails: false,
      sourceList: [], // 来源列表
      updateLog: [], // 修改记录
      activeNames: -1, // 打开的记录

      form: {
        name: '',
        realname: '',
        type: 0,
        mobile: '',
        spare_mobile: [''],
        telephone: [''],
        email: [''],
        position: '',
        company: [''],
        wechat: [''],
        qq: [''],
        tencent_id: [''],
        source: '',
        one_log: '',
        remarks: ''
      },
      formRules: {
        name: [
          { required: true, message: '请输入客户昵称', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择客户类型', trigger: 'blur' }
        ],
        source: [
          { required: true, message: '请选择客户来源', trigger: 'blur' }
        ]
      },
      submitDisabled: false
    }
  },
  watch: {},
  created() {
    this.title = this.$route.query.title
    if (this.$route.query.id) {
      if (this.title === '客户详情') {
        this.isDetails = true
      }
      this.id = this.$route.query.id
      this.getCustomerInfo(this.$route.query.id)
    }
    this.getSourceList()
  },
  methods: {
    /**
     *  获取用户信息
     *  接口:'customer/detail/{id}'
     */
    getCustomerInfo(id) {
      const url = 'customer/detail/' + id
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.form = res.data
        if (!this.isDetails) {
          this.form.spare_mobile = res.data.spare_mobile ? res.data.spare_mobile.split(',') : [''];
          this.form.qq = res.data.qq ? res.data.qq.split(',') : [''];
          this.form.wechat = res.data.wechat ? res.data.wechat.split(',') : [''];
          this.form.email = res.data.email ? res.data.email.split(',') : ['']
          this.form.company = res.data.company ? res.data.company.split(',') : [''];
          this.form.telephone = res.data.telephone ? res.data.telephone.split(',') : [''];
          this.form.tencent_id = res.data.tencent_id ? res.data.tencent_id.split(',') : [''];
        }
        this.getUpdateLog()
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取来源列表
     *  接口:'member/source-list'
     */
    getSourceList() {
      const url = 'member/source-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.sourceList = res.data
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取修改记录
     *  接口:'customer/updateLog'
     */
    getUpdateLog() {
      const url = 'customer/updateLog/' + this.id
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.updateLog = res.data.reverse()
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    // 动态删除项
    removeItem(paramsName, item) {
      const index = this.form[paramsName].indexOf(item)
      if (index !== -1) {
        this.form[paramsName].splice(index, 1)
      }
    },
    // 动态增加项
    addItem(paramsName) {
      this.form[paramsName].push('')
    },

    toModify() {
      this.isDetails = false
      this.form.spare_mobile = this.form.spare_mobile ? this.form.spare_mobile.split(',') : ['']
      this.form.qq = this.form.qq ? this.form.qq.split(',') : ['']
      this.form.wechat = this.form.wechat ? this.form.wechat.split(',') : ['']
      this.form.company = this.form.company ? this.form.company.split(',') : ['']
      this.form.telephone = this.form.telephone ? this.form.telephone.split(',') : ['']
      this.form.tencent_id = this.form.tencent_id ? this.form.tencent_id.split(',') : ['']
      this.form.email = this.form.email ? this.form.email.split(',') : ['']
    },

    /**
     * 表单提交
     * 添加客户
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!validatNonSpecialCharactersNonPureNumber(this.form.name)) {
            this.$message.error('客户名称不能包含特殊字符及纯数字');
            return;
          }
          if (!validatNonSpecialCharacters(this.form.mobile)) {
            this.$message.error('客户主要联系方式不能包含特殊字符');
            return;
          }
          const data = Object.assign({}, this.form)

          data.spare_mobile && (data.spare_mobile = data.spare_mobile.join(','))
          data.qq && (data.qq = data.qq.join(','))
          data.wechat && (data.wechat = data.wechat.join(','))
          data.company && (data.company = data.company.join(','))
          data.telephone && (data.telephone = data.telephone.join(','))
          data.email && (data.email = data.email.join(','))
          data.tencent_id && (data.tencent_id = data.tencent_id.join(','))
          const url = this.id ? (this.title === '客户激活' ? 'customer/ajax/' + this.id : 'customer/edit/' + this.id) : 'customer/create'
          this.title === '客户激活' && (data.action = 'active_customer')
          this.submitDisabled = true;
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg)
            this.$router.back(-1);
          }).catch(e => {
            if (!this.id) {
              data['is_update'] = 1;
              this.$store.dispatch('GetConnect', { url, data }).then(res => {
                this.submitDisabled = false;
                this.$message.success(res.msg)
                this.$router.back(-1);
              })
              // this.$confirm(e.msg, '提示', {
              //   confirmButtonText: '确定',
              //   cancelButtonText: '取消',
              //   type: 'warning'
              // }).then(() => {
              //   data['is_update'] = 1;
              //   this.$store.dispatch('GetConnect', { url, data }).then(res => {
              //     this.submitDisabled = false;
              //     this.$message.success(res.msg)
              //     this.$router.back(-1);
              //   })
              // })
            } else {
              this.submitDisabled = false;
              this.$message.error(e.msg)
            }
          })
        } else {
          this.submitDisabled = false;
          this.$message.error('提交失败,请检查必填项')
        }
      })
    },
    cancel() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../styles/index.scss';
.box-1 {
  max-width: 1000px;
  margin: 0 auto;
  > div span {
    font-size: 18px;
    font-weight: 600;
    padding: 0 10px;
  }
  .el-form {
    max-width: 900px;
    .title {
      font-weight: 600;
    }
    .remark {
      font-size: 13px;
      color: $textGray;
    }
    > div >.el-button {
      @extend .bg-green;
      width: 20%;
      min-width: 160px;
    }
  }
}
.el-checkbox {
  margin-right: 30px;
}
.el-checkbox + .el-checkbox {
  margin-left: 0;
  margin-right: 30px;
}
.pre {
   white-space: pre-wrap;
   word-wrap: break-word;
   line-height: 30px;
   margin: 10px 0;
 }
</style>
